<template>
  <div class="login-container">
    <el-card class="box-card">
      <template #header>
        <div class="card-header">
          <span>登录</span>
        </div>
      </template>
      <el-form :model="loginForm" :rules="rules" ref="loginFormRef" label-width="80px">
        <el-form-item label="用户名" prop="username">
          <el-input v-model="loginForm.username"></el-input>
        </el-form-item>
        <el-form-item label="密码" prop="password">
          <el-input type="password" v-model="loginForm.password" show-password></el-input>
        </el-form-item>
        <el-form-item>
          <el-button type="primary" @click="submitForm">登录</el-button>
          <el-button @click="resetForm">重置</el-button>
        </el-form-item>
      </el-form>
    </el-card>
  </div>
</template>

<script>
import { reactive, ref } from 'vue';
import { ElMessage } from 'element-plus';
// import { useRouter } from 'vue-router';
import axios from '@/utils/request.js'

export default {
  // setup 是vue3的一个默认方法，实现组合式组建的开发
  setup() {
    // ref方法定义一个变量，并且初始化赋值，同时让这个变量可以在模板中使用
    const loginFormRef = ref(null);
    // reactive定义一个响应式对象
    const loginForm = reactive({
      username: '',
      password: '',
    });
    // 定义表单验证规则
    const rules = reactive({
      username: [
        { required: true, message: '请输入用户名', trigger: 'blur' },
      ],
      password: [
        { required: true, message: '请输入密码', trigger: 'blur' },
      ],
    });

    // 定义一个方法submitForm
    const submitForm = () => {
      loginFormRef.value.validate((valid) => {
        if (valid) {
          axios(
            {
              url:'/login.do',
              method:'post',
             params:{
              name:loginForm.username,
              pass:loginForm.password
             },
            } )
            .then((res)=>{
              if(res.result=='success'){
                window.location.href = '/main';
              }else{
                ElMessage.error('请输入正确的用户名和密码');
                return false;

              }
              
              // console.log(res);
              // localStorage.setItem('token',res.data.token);
            }
           
            
          )

          // 这里可以添加登录逻辑，例如调用API进行验证
          //导向主界面
          // window.location.href = '/main';
        } else {
          ElMessage.error('请输入正确的用户名和密码');
          return false;
        }
      });
    };

    // 定义一个方法resetForm,clearFields方法可以重置表单
    const resetForm = () => {
      loginFormRef.value.resetFields();
    };

    // 定义的所有东西都return出去，这样在模板中才能使用
    return {
      loginFormRef,
      loginForm,
      rules,
      submitForm,
      resetForm,
    };
  },
};
</script>

<style scoped>
.login-container {
  display: flex;
  justify-content: center;
  align-items: center;
  height: 100vh;
  width: 100vw;
  background-color: #f0f2f5;
}

.box-card {
  width: 400px;
}
</style>


<!-- 
const 方法名 = （参数）{

};

const 方法名 = (参数) => {

};
-->